﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace _04_BackgroundWorker
{
    public partial class Form1 : Form
    {
        BackgroundWorker worker = new BackgroundWorker();
        public Form1()
        {
            InitializeComponent();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
            worker.WorkerSupportsCancellation = true;
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Completed");
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            RunProgress();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hello, worker");
        }

        void RunProgress()
        {
            for(int i = 0; i < 100; i++)
            {
                if (progressBar1.Value < progressBar1.Maximum)
                {
                    if (worker.CancellationPending) break;
                    progressBar1.Value += 5;
                    Thread.Sleep(1000);
                }
            }
        }

        private void bStart_Click(object sender, EventArgs e)
        {
            //RunProgress();
            worker.RunWorkerAsync();
        }

        private void bStop_Click(object sender, EventArgs e)
        {
            worker.CancelAsync();
        }
    }
}
